<?php

class SiteController extends Controller {
    
    /**
    * Declares class-based actions.
    */
    public function actions() {
        return array(
            // captcha action renders the CAPTCHA image displayed on the login page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
                'testLimit' => 1,
            ),
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    /**
     * @return array action filters
     */
    public function filters() {
        return array();
    }

    /**
    * This is the default 'index' action that is invoked
    * when an action is not explicitly requested by users.
    */
    public function actionIndex() {
        if(Yii::app()->user->isGuest)
            $this->actionLogin();
        else
            $this->redirect(Yii::app()->user->getDefaultUrl());
    }

    /**
     * This is the login action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionLogin() {
        $model = new Login;
        
        if(Yii::app()->captcha->isMaxLoginTryExceeded())
            $model->scenario = Yii::app()->captcha->getScenarioNameCaptchaRequired();
        
        $this->performAjaxValidation($model);
        
        if(isset($_POST['Login'])) {
            $model->attributes = $_POST['Login'];

            // validate user input and redirect to the previous page if valid
            if($model->validate() && $model->login()) {
                Yii::app()->captcha->unsetSessionErrorLogin();

                if(Yii::app()->user->returnUrl == null || Yii::app()->user->returnUrl == '')
                    $this->redirect(Yii::app()->user->getDefaultUrl());
                else
                    $this->redirect(Yii::app()->user->returnUrl);
            }
            else 
                Yii::app()->captcha->increaseSessionErrorLogin();
        }

        // display the login form
        $this->render('login', array('model' => $model));
    }

    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }
	
    /**
     * This is the action to handle external exceptions.
     */
    public function actionError() {
        if($error = Yii::app()->errorHandler->error) {
            if(Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    // Configuring cron job (linux) to request this page every minute with wget:
    // 1) Create a cron job file:           crontab -e
    // 2) Insert on vi a line like that:    minuto hora dia mes dia-da-semana comando
    // 3) For every minute it will be:      */1 * * * * wget -O - -q -t 1 http://localhost/matriz-de-sincronizacao/site/notifyresponsible

    /**
     * Notifies activities responsibles by email and sms, once requested by localhost (127.0.0.1)
     * It'll be called every minute by cron job (locally)
     * @throws CHttpException
     */
    public function actionNotifyResponsible() {
        if ($_SERVER['SERVER_ADDR'] != '127.0.0.1')
            throw new CHttpException(403, 'Acesso proibido.');

        $todayActivities = Atividade::model()->with('Usuario')->findAllByAttributes(array('data' => date('Y-m-d')));
        $currentTime = date('H:i:s');

        foreach($todayActivities as $index => $activity) {
            $message = NULL;
            if($activity->hora_alerta_proximidade == $currentTime)
                $message = sprintf('A atividade "%s" está em %s.', $activity->descricao, 'execução');

            else if($activity->hora_conclusao == $currentTime)
                $message = sprintf('A atividade "%s" está em %s.', $activity->descricao, 'alerta');

            else if(DateHelper::addMinutesToDate($activity->hora_conclusao, $activity->tolerancia_atraso) == $currentTime)
                $message = sprintf('A atividade "%s" está em %s.', $activity->descricao, 'atraso');

            if(!is_null($message)) {
                try {
                    $this->sendEmail($activity->email_responsavel_atividade, $message);
                    $this->sendEmail($activity->Usuario->email_responsavel_orgao, $message);

                    $this->sendSMS($activity->telefone_responsavel_atividade, $message);
                    $this->sendSMS($activity->Usuario->telefone_responsavel_orgao, $message);
                }
                catch(Exception $ex) {
                    echo 'Erro no tratamento de: ' . $message;
                }
            }
        }
    }

    /**
     * Sends email by given email and message
     * @param $email
     * @param $message
     */
    private function sendEmail($email, $message) {
        $emailSender = Yii::app()->params['adminEmail'];

        $headers  = "MIME-Version: 1.1\r\n";
        $headers .= "Content-type: text/html; charset=utf-8\r\n";
        $headers .= "From: Matriz de sincronização <" . $emailSender . ">\r\n";
        $headers .= "Reply-To: Matriz de sincronização <" . $emailSender . ">\r\n";

        $subject = "Notificação de atividade";

        if (filter_var($email, FILTER_VALIDATE_EMAIL))
            mail($email, $subject, $message, $headers, "-r" . $emailSender);
    }

    /**
     * Sends SMS by given phone and number
     * @param $phone
     * @param $message
     */
    private function sendSMS($phone, $message) {
        //preg_replace changes from storage pattern (12) 3456-7890 to 1234567890
        Yii::app()->sms->send(array(
                'to' => sprintf('55%s', preg_replace('/[(](\d+)[)]\s(\d+)[-](\d+)/i', '$1$2$3', $phone)),
                'message' => $message
            )
        );
    }

    /**
     * Performs the AJAX validation.
     * @param Login $model the model to be validated
     */
    protected function performAjaxValidation($model) {
        if(isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}